package com.uinnova.product.eam.workable.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Component
public class HttpUtil {

    @Autowired
    private RestTemplate restTemplate;

    public String get(String url) {
        return get(url, String.class);
    }

    public <T> T get(String url, Class<T> tClass) {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.set("Quickea-Eam", "quickea-eam");
        HttpEntity requestEntity = new HttpEntity(requestHeaders);
        ResponseEntity<T> responseEntity = restTemplate.exchange(url, HttpMethod.GET,requestEntity,tClass);
        return processResult(responseEntity);
    }

    /**
     * post请求
     * @param url
     * @param requestBody
     * @return
     */
    public String post(String url, Object requestBody) {
        return post(url, requestBody, String.class);
    }

    public <T> T post(String url, Object requestBody, Class<T> t) {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.set("Quickea-Eam", "quickea-eam");
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        requestHeaders.setContentType(type);
        HttpEntity<String> requestEntity = new HttpEntity<>(JSON.toJSONString(requestBody),requestHeaders);
        ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, requestEntity, t);
        return processResult(responseEntity);
    }

    /**
     * 解析返回值
     * @param responseEntity
     * @return
     * @param <T>
     */
    private <T> T processResult(ResponseEntity<T> responseEntity) {
        if (HttpStatus.OK.equals(responseEntity.getStatusCode())) {
            return responseEntity.getBody();
        } else {
            log.error("http response code :{}", responseEntity.getStatusCode());
        }
        return null;
    }

}
